package com.ruoyi.system.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysCodingRule;
import com.ruoyi.system.service.ISysCodingRuleService;
import com.ruoyi.system.service.ISysCodingService;
import com.ruoyi.system.service.ISysCodingRuleSegmentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 编码生成Controller
 * 
 * @author ruoyi
 * @date 2025-08-08
 */
@RestController
@RequestMapping("/system/coding")
public class SysCodingController extends BaseController
{
    @Autowired
    private ISysCodingRuleService sysCodingRuleService;
    
    @Autowired
    private ISysCodingService sysCodingService;
    
    @Autowired
    private ISysCodingRuleSegmentService sysCodingRuleSegmentService;
    


    /**
     * 查询编码规则列表
     */
    @PreAuthorize("@ss.hasPermi('system:coding:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysCodingRule sysCodingRule)
    {
        startPage();
        List<SysCodingRule> list = sysCodingRuleService.selectSysCodingRuleList(sysCodingRule);
        return getDataTable(list);
    }
    


    /**
     * 导出编码规则列表
     */
    @PreAuthorize("@ss.hasPermi('system:coding:export')")
    @Log(title = "编码规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysCodingRule sysCodingRule)
    {
        List<SysCodingRule> list = sysCodingRuleService.selectSysCodingRuleList(sysCodingRule);
        ExcelUtil<SysCodingRule> util = new ExcelUtil<SysCodingRule>(SysCodingRule.class);
        util.exportExcel(response, list, "编码规则数据");
    }

    /**
     * 获取编码规则详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:coding:query')")
    @GetMapping(value = "/{ruleId}")
    public AjaxResult getInfo(@PathVariable("ruleId") Long ruleId)
    {
        return success(sysCodingRuleService.selectSysCodingRuleByRuleId(ruleId));
    }

    /**
     * 新增编码规则
     */
    @PreAuthorize("@ss.hasPermi('system:coding:add')")
    @Log(title = "编码规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysCodingRule sysCodingRule)
    {
        return toAjax(sysCodingRuleService.insertSysCodingRule(sysCodingRule));
    }

    /**
     * 修改编码规则
     */
    @PreAuthorize("@ss.hasPermi('system:coding:edit')")
    @Log(title = "编码规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysCodingRule sysCodingRule)
    {
        return toAjax(sysCodingRuleService.updateSysCodingRule(sysCodingRule));
    }

    /**
     * 删除编码规则
     */
    @PreAuthorize("@ss.hasPermi('system:coding:remove')")
    @Log(title = "编码规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ruleIds}")
    public AjaxResult remove(@PathVariable Long[] ruleIds)
    {
        return toAjax(sysCodingRuleService.deleteSysCodingRuleByRuleIds(ruleIds));
    }

    /**
     * 根据表名和字段名生成临时编码（不更新流水号）
     */
    @PostMapping("/generate")
    public AjaxResult generateCode(@RequestBody Map<String, Object> params)
    {
        String tableName = (String) params.get("tableName");
        String fieldName = (String) params.get("fieldName");
        
        if (tableName == null || fieldName == null) {
            return error("表名和字段名不能为空");
        }
        
        try {
            // 生成临时编码（预览模式，不更新流水号）
            String code = sysCodingService.previewCode(params);
            return AjaxResult.success("编码生成成功").put("data", code);
        } catch (Exception e) {
            e.printStackTrace();
            return error("编码生成失败: " + e.getMessage());
        }
    }
    
    /**
     * 确认编码并更新流水号（保存表单时调用）
     */
    @PreAuthorize("@ss.hasPermi('system:coding:confirm')")
    @PostMapping("/confirm")
    public AjaxResult confirmCode(@RequestBody Map<String, Object> params)
    {
        String tableName = (String) params.get("tableName");
        String fieldName = (String) params.get("fieldName");
        
        if (tableName == null || fieldName == null) {
            return error("表名和字段名不能为空");
        }
        
        try {
            // 正式生成编码并更新流水号
            String code = sysCodingService.generateCode(tableName, fieldName, params);
            return AjaxResult.success("编码确认成功").put("data", code);
        } catch (Exception e) {
            e.printStackTrace();
            return error("编码确认失败: " + e.getMessage());
        }
    }

    /**
     * 编码预览
     */
    @PreAuthorize("@ss.hasPermi('system:coding:preview')")
    @PostMapping("/preview")
    public AjaxResult previewCoding(@RequestBody Map<String, Object> params)
    {
        try {
            String preview = sysCodingService.previewCode(params);
            return success(preview);
        } catch (Exception e) {
            return error("编码预览失败: " + e.getMessage());
        }
    }

    /**
     * 批量生成编码
     */
    @PreAuthorize("@ss.hasPermi('system:coding:batch')")
    @PostMapping("/batch")
    public AjaxResult batchGenerateCode(@RequestBody Map<String, Object> params)
    {
        try {
            List<String> codes = sysCodingService.batchGenerateCode(params);
            return success(codes);
        } catch (Exception e) {
            return error("批量生成编码失败: " + e.getMessage());
        }
    }

    /**
     * 获取编码规则统计信息
     */
    @PreAuthorize("@ss.hasPermi('system:coding:stats')")
    @GetMapping("/stats")
    public AjaxResult getCodingStats()
    {
        try {
            Map<String, Object> stats = sysCodingService.getCodingStats();
            return success(stats);
        } catch (Exception e) {
            return error("获取统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 验证编码规则配置
     */
    @PreAuthorize("@ss.hasPermi('system:coding:validate')")
    @PostMapping("/validate")
    public AjaxResult validateCodingRule(@RequestBody Map<String, Object> params)
    {
        try {
            boolean isValid = sysCodingService.validateCodingRule(params);
            return success(isValid);
        } catch (Exception e) {
            return error("验证编码规则失败: " + e.getMessage());
        }
    }

    /**
     * 复制编码规则
     */
    @PreAuthorize("@ss.hasPermi('system:coding:copy')")
    @PostMapping("/copy/{ruleId}")
    public AjaxResult copyCodingRule(@PathVariable Long ruleId, @RequestBody Map<String, Object> params)
    {
        try {
            String newRuleName = (String) params.get("newRuleName");
            boolean result = sysCodingService.copyCodingRule(ruleId, newRuleName);
            return toAjax(result);
        } catch (Exception e) {
            return error("复制编码规则失败: " + e.getMessage());
        }
    }

    /**
     * 启用/禁用编码规则
     */
    @PreAuthorize("@ss.hasPermi('system:coding:status')")
    @PutMapping("/status/{ruleId}/{status}")
    public AjaxResult toggleCodingStatus(@PathVariable Long ruleId, @PathVariable String status)
    {
        try {
            boolean result = sysCodingService.toggleCodingStatus(ruleId, status);
            return toAjax(result);
        } catch (Exception e) {
            return error("修改编码规则状态失败: " + e.getMessage());
        }
    }

    /**
     * 导入编码规则
     */
    @PreAuthorize("@ss.hasPermi('system:coding:import')")
    @PostMapping("/import")
    public AjaxResult importCoding(@RequestBody Map<String, Object> params)
    {
        try {
            boolean result = sysCodingService.importCoding(params);
            return toAjax(result);
        } catch (Exception e) {
            return error("导入编码规则失败: " + e.getMessage());
        }
    }
}